package com.hliushi.learn.service;

import com.hliushi.learn.entity.TFile;
import com.hliushi.learn.model.FileCustom;
import com.hliushi.learn.repository.TFileRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * TFile service层
 *
 * @author auto generated
 * @date 2021-08-17 11:02:03
 */
@Slf4j
@Service
public class TFileService {

    @Resource
    private TFileRepository rep;

    /**
     * 获取某文件类型为备份的文件
     *
     * @param fileType 文件类型
     * @param count    获取个数
     * @return List<FileCustom>
     */
    public List<FileCustom> fetchUnBackupFiles(String fileType, Integer count) {
        List<TFile> vedio2 = rep.findByTypeNative(fileType, count);
        List<FileCustom> files = new ArrayList<>();

        // Hibernate: select * from t_file where type = ? order by id asc limit ?
        // FileCustom(id=31, name=文件31, type=vedio, content=content31, backedUp=null)
        // FileCustom(id=32, name=文件32, type=vedio, content=content32, backedUp=null)
        // FileCustom(id=33, name=文件33, type=vedio, content=content33, backedUp=null)
        // FileCustom(id=34, name=文件34, type=vedio, content=content34, backedUp=null)
        // FileCustom(id=35, name=文件35, type=vedio, content=content35, backedUp=null)
        vedio2.forEach(item -> {
            FileCustom fileCustom = new FileCustom();
            BeanUtils.copyProperties(item, fileCustom);
            files.add(fileCustom);
        });

        return files;
    }


    /**
     * 备份文件
     *
     * @param files 要备份的文件
     */
    @Transactional
    public void backupFiles(List<FileCustom> files) {
        for (FileCustom file : files) {
            rep.updateBackup(file.getId());
            log.info("线程 {} | 已备份文件:{}  文件类型:{}",
                    Thread.currentThread().getId(),
                    file.getName(), file.getType());
        }
    }

}
